package workorder

import (
	"../common"
	"../web"
	"strings"
)

type GenerateSsnObj struct {
	common.BaseHandler
}

func (self *GenerateSsnObj) Prepare() {
	wonos := *common.FetchAllRowsPtr(
		`SELECT WONO 
           FROM SFC_WO(NOLOCK) 
          WHERE RELEASED = 0 
            AND LOCKED = 0 
            AND CLOSED = 0 
          ORDER BY WONO`,
		self.Usr.Conn, new(common.WorkOrderNo))

	self.TmplData["wonos"] = wonos
}

func (self *GenerateSsnObj) ParameterCheck() bool {
	status := common.GetScanStatus(self.Ctx, "GENERATESSN")
	if !status {
		self.TmplData["error"] = common.GetText(self.Lang,
			"System is busy, please wait a moment and try again.")
		return false
	}

	s_wono := self.Ctx.Params["wono"]
	if s_wono == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the WorkOrder.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_wono)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{strings.ToUpper(s_wono)}

	return true
}

func (self *GenerateSsnObj) SqlExecute() bool {
	common.SetScanStatus(self.Ctx, "GENERATESSN", false)
	spRtnData := *common.FetchOneRowPtr(
		`sp_GenerateSSN ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	common.SetScanStatus(self.Ctx, "GENERATESSN", true)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	return true
}

func GenerSSNHandler(ctx *web.Context) {
	self := new(GenerateSsnObj)
	self.Ctx = ctx
	self.Url = "/generatesn"
	self.Html = "generatesn.html"
	self.Rightlist = []string{"generatesn"}
	self.Flashstr = "Generate Serial No.: [ %v ] finished."
	self.Do(self)
}
